import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/user/institution/industry.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/widget_extension_utils.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:universal_html/html.dart' as html;
import '../../../network/Api.dart';
import '../../../utils/loading.dart';
import '../../../utils/page.dart';
import '../../../widget/icon_text.dart';
import '../../cooperation/address/address_manage_page.dart';
import '../../cooperation/shop_code/shop_promote_code_page.dart';
import '../../cooperation/shop_name/shop_name_edit_page.dart';
import '../../cooperation/shop_name/shop_open_time_page.dart';
import '../../cooperation/shop_name/shop_phone_edit_page.dart';
import '../matchMaker/maker_manager.dart';
import '../matchMaker/maker_upgrade.dart';
import '../matchMaker/matchMaker.dart';
import '../wallet.dart';
import 'companyPodfile.dart';

import 'institution_edit_controller.dart';

class institutionUi extends StatefulWidget {
  String come;
  int perType;
  int busType;

  institutionUi(this.come, {Key? key, this.perType = 0, this.busType = 0})
      : super(key: key);

  @override
  State<institutionUi> createState() => _institutionUiState();
}

class _institutionUiState extends State<institutionUi> {
  late File image;
  bool _switchSelected = false;
  String level = '';
  bool sss = false;
  late String _avatarFilePath = "";
  String industry = '';
  final _user = <String, dynamic>{};
  late Map<String, dynamic> _userInfo = {};
  double rightTextMaxWidth = 1.sw - 100;
  InstitutionEditController editController =
      Get.put(InstitutionEditController());

  bool isShow = true; //是否显示推广二维码、管理等 个人红娘隐藏掉

  @override
  void initState() {
    super.initState();
    _getData();
  }

  void _getData() {
    loading(() async {
      final res = await Api.getInstance().makerManager(2);
      if (res['code'] == 0) {
        setState(() {
          _userInfo = res['data'];
          isShow = _userInfo['matchType'] == 1 ? false : true;
          if (_userInfo['level'] == 1) {
            level = '2维普通红娘';
          } else if (_userInfo['level'] == 2) {
            level = '3维热心红娘';
          } else if (_userInfo['level'] == 3) {
            level = '5维银牌红娘';
          } else if (_userInfo['level'] == 4) {
            level = '7维金牌红娘';
          } else if (_userInfo['level'] == 5) {
            level = '9维至尊红娘';
          }
        });
      } else {
        toast(res['msg']);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      title: "店铺设置",
      rightActions: [
        widget.come == '1'
            ? Center(
                child: Container(
                  padding: const EdgeInsets.only(right: 15),
                  child: GestureDetector(
                    onTap: () {
                      Navigate.toMain();
                      // Navigator.of(navKey.currentState!.overlay!.context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => const PersonalUi()), (route) => route == null);
                    },
                    child: Text(
                      '回到主页',
                      style: TextStyle(color: ThemeColor.appColor),
                    ),
                  ),
                ),
              )
            : Container(
                padding: const EdgeInsets.only(right: 14),
                child: Row(
                  children: [
                    Image.asset(
                      'images/map/dpsz_change_icon.png',
                      width: 16,
                    ),
                    const SizedBox(
                      width: 6,
                    ),
                    Text(
                      '切换身份',
                      style: TextStyle(
                          fontSize: 14, color: ThemeColor.gray4C4C4CColor),
                    )
                  ],
                ),
              ).clickAction(tapAction: () {
                if (widget.perType == 0) {
                  Navigate.toPage(const matchMakerUI('个人红娘'));
                } else if (widget.perType == 1) {
                  Get.off(MakerManagerPage(
                    '2',
                    busType: widget.busType,
                    perType: widget.perType,
                  ));
                }
              }),
      ],
      childWidget: SingleChildScrollView(
        child:  Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildActionButton(
                "商家头像", 'avtar', true, true, false, false, false),
            _buildActionButton(
                "商家名称", 'name', true, false, false, false, false),
            _buildActionButton(
                "商家简称", 'forshort', true, false, false, false, false),
            _buildActionButton(
                "简介", 'introuce', true, false, false, false, false),
            _buildActionButton(
                "商家电话", 'tel', false, false, false, true, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton("红娘等级", 'makerLevel', true, false,
                false, false, false),
            _buildActionButton(
                "有效日期", 'date', true, false, false, false, false),
            _buildActionButton("红娘续费", 'makerAgainMoney', false,
                false, false, false, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton("行业选择", 'workSelect', true, false,
                false, false, false),
            _buildActionButton("营业时间", 'workDate', false, false,
                false, false, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton(
                "地址", 'adress', true, false, false, false, false),
            _buildActionButton("-隐藏地址", 'hiddenadress', false, false,
                true, false, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton("是否在首页红娘展示", 'hiddenmarker', false,
                false, true, false, false),
            Divider(
                thickness: 5,
                color: ThemeColor.sendMsgColor,
                indent: 0,
                endIndent: 0),
            _buildActionButton("推广二维码", 'code', false, false,
                false, false, true),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton("员工管理", 'member', true, false,
                false, false, false),
            _buildActionButton("会员管理", 'manager', true, false,
                false, false, false),
            _buildActionButton("我推荐的商家", 'referrer', true, false,
                false, false, false),
            _buildActionButton("群管理", 'group', false, false,
                false, false, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton("活动管理", 'active', true, false,
                false, false, false),
            _buildActionButton("收入管理", 'income', true, false,
                false, false, false),
            _buildActionButton("管理员管理", 'emploper', false,
                false, false, false, false),
            Divider(
              thickness: 5,
              color: ThemeColor.sendMsgColor,
            ),
            _buildActionButton(
                "红娘升级", 'upgrade', false, false, false, false, false),
          ],
        ),
      ),
    );
  }

  /// 标题栏
  Widget _buildActionBar() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const Expanded(
          child: SizedBox(),
        ),
        GestureDetector(
            onTap: () {
              _onClick("EDIT");
            },
            child: Container(
                width: 48,
                height: 48,
                alignment: Alignment.center,
                child: Text(
                  "编辑",
                  style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
                ))),
        const SizedBox(
          width: 6,
        )
      ],
    );
  }

  /// 功能按钮
  Widget _buildActionButton(String s, String id, bool isDiverder, bool avtar,
      bool swit, bool text, bool code) {
    if (id == 'makerLevel' ||
        id == 'date' ||
        id == 'hiddenadress' ||
        id == 'hiddenmarker') {
      sss = true;
    } else {
      sss = false;
    }
    return GestureDetector(
        onTap: () {
          _onClick(id);
        },
        child: s == ""
            ? Container(
                height: 5,
                color: ThemeColor.dividerColor,
              )
            : Container(
                height: 52,
                margin: const EdgeInsets.symmetric(horizontal: 14),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                  width: 1,
                  color: isDiverder == true
                      ? ThemeColor.dividerColor
                      : Colors.white,
                ))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          s,
                          style: TextStyle(
                              color: ThemeColor.textColor, fontSize: 16),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        avtar == true
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: Image(
                                  image: CachedNetworkImageProvider(
                                      Provider.fixAvatar(_avatarFilePath
                                              .isNotEmpty
                                          ? _avatarFilePath
                                          : _userInfo['profilePhoto'] ?? '')),
                                  height: 30,
                                  width: 30,
                                ),
                              )
                            : Container(),
                        id == 'tel'
                            ? Text(
                                _userInfo['mobilePhone'] ?? '',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Color(
                                      0xFFB5B5B5,
                                    )),
                              )
                            : Container(),
                        id == 'makerLevel'
                            ? IconText(
                                level,
                                style: const TextStyle(
                                    fontSize: 14, color: Color(0xFFB5B5B5)),
                                icon: Container(
                                  padding: const EdgeInsets.only(left: 5),
                                  child: Image.asset(
                                    'images/maker_${_userInfo['level'] ?? 1}.png',
                                    width: 21,
                                    height: 21,
                                  ),
                                ),
                                beforeText: false,
                              )
                            : Container(),
                        id == 'name'
                            ? Text(
                                _userInfo['matchName'] ?? '',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Color(
                                      0xFFB5B5B5,
                                    )),
                              )
                            : Container(),
                        id == 'date'
                            ? Text(
                                _userInfo['validDate'] ?? '',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Color(
                                      0xFFB5B5B5,
                                    )),
                              )
                            : Container(),
                        id == 'forshort'
                            ? Container(
                                constraints: BoxConstraints(
                                    maxWidth: rightTextMaxWidth - 20.w),
                                child: Text(
                                  _userInfo['shortName'] ?? '',
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                      fontSize: 14,
                                      color: Color(
                                        0xFFB5B5B5,
                                      )),
                                ),
                              )
                            : Container(),
                        id == 'workDate'
                            ? Row(
                                children: [
                                  Text(
                                    (_userInfo['openTime'] == null ||
                                            _userInfo['openTime'] == '')
                                        ? '开始时间'
                                        : _userInfo['openTime'],
                                    overflow: TextOverflow.ellipsis,
                                    style: const TextStyle(
                                        fontSize: 14,
                                        color: Color(
                                          0xFFB5B5B5,
                                        )),
                                  ),
                                  const Text(
                                    '-',
                                    style: TextStyle(
                                        fontSize: 14,
                                        color: Color(
                                          0xFFB5B5B5,
                                        )),
                                  ),
                                  Text(
                                    (_userInfo['endTime'] == null ||
                                            _userInfo['endTime'] == '')
                                        ? '结束时间'
                                        : _userInfo['endTime'],
                                    overflow: TextOverflow.ellipsis,
                                    style: const TextStyle(
                                        fontSize: 14,
                                        color: Color(
                                          0xFFB5B5B5,
                                        )),
                                  ),
                                ],
                              )
                            : Container(),
                        id == 'introuce'
                            ? Container(
                                constraints:
                                    BoxConstraints(maxWidth: rightTextMaxWidth),
                                child: Text(
                                  _userInfo['introduce'] ?? '',
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                      fontSize: 14,
                                      color: Color(
                                        0xFFB5B5B5,
                                      )),
                                ),
                              )
                            : Container(),
                        id == 'workSelect'
                            ? Text(
                                _userInfo['trade'] ?? '',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Color(
                                      0xFFB5B5B5,
                                    )),
                              )
                            : Container(),
                        swit == true
                            ? CupertinoSwitch(
                                value: _switchSelected,
                                activeColor: ThemeColor.appColor,
                                onChanged: (value) {
                                  setState(() {
                                    _switchSelected = value;
                                  });
                                })
                            : Container(),
                        code == true
                            ? Image.asset(
                                "images/ic_jigouCode.png",
                                width: 16,
                                height: 16,
                              )
                            : Container(),
                        sss == false
                            ? Icon(
                                Icons.arrow_forward_ios,
                                color: ThemeColor.textColorSecond,
                                size: 15,
                              )
                            : Container()
                      ],
                    ),
                  ],
                ),
              ));
  }

  _onClick(String id) async {
    switch (id) {
      case 'avtar':
        //商家头像
        // _selectPhoto(context);
        break;
      case 'name':
        //商家名称

        break;
      case 'forshort':
        {
          Get.to(ShopNameEditPage(
            resMap: _userInfo,
            refreshBlock: () {
              _getData();
            },
          ));
        }

        break;
      case 'workDate':
        {
          Get.to(ShopOpenTimePage(
            resMap: _userInfo,
            refreshBlock: () {
              _getData();
            },
          ));
        }

        break;
      case 'introuce':
        {
          //简介
          Navigator.of(context).push(MaterialPageRoute(
              builder: (builder) => CompanyProfileView(
                    resMap: _userInfo,
                    refreshBlock: () {
                      _getData();
                    },
                  )));
        }

        break;
      case 'tel':
        //商家电话
        Get.to(ShopPhoneEditPage(
          resMap: _userInfo,
          refreshBlock: () {
            _getData();
          },
        ));
        break;
      case 'makerAgainMoney':
        //红娘续费

        break;
      case 'workSelect':
        //行业选择
        final res = await BottomSheetDialog.show(context, IndustryPage());
        if (res) {
          _getData();
        }
        break;
      case 'code':
        //推广二维码
        Get.to(ShopPromoteCodePage(
          resMap: _userInfo,
        ));
        break;
      case 'manager':
        //会员管理

        break;
      case 'referrer':
        Get.toNamed(PageRouteNames.memberList);
        break;
      case 'member':
        Get.toNamed(PageRouteNames.memberList,arguments: _userInfo['id']);
        break;
      case 'group':
        //群管理
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const integranlInstitionUI()));
        break;
      case 'active':
        //活动管理

        break;
      case 'income':
        //收入管理
        Navigate.toPage(const WalletUi());
        break;
      case 'emploper':
        //管理员管理

        break;
      case 'upgrade':
        //红娘升级
        Navigate.toPage(MakerUpgradePage(_userInfo, level));
        break;

      case 'adress':
        //地址
        Get.to(AddressManagePage(
          resMap: _userInfo,
          refreshBlock: () {
            _getData();
          },
        ));
        break;
    }
  }

  //头像
  Future<void> _selectPhoto(context) async {
    double width = MediaQuery.of(context).size.width;
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
            color: Colors.white,
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: () {
                          getAlbumImg('拍照');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('拍照'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          getAlbumImg('相册');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 60,
                          color: Colors.white,
                          child: const Text('从手机相册选择'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('取消'),
                        ))
                  ],
                )));
      },
    );
  }

  void getAlbumImg(String type) {
    Navigator.pop(context);
    if (kIsWeb) {
      loading(() async {
        final uploadInputElement = html.FileUploadInputElement();
        uploadInputElement.multiple = false;
        uploadInputElement.draggable = true;
        uploadInputElement.click();
        uploadInputElement.onChange.listen((event) {
          final file = uploadInputElement.files?.first;

          if (file != null) {
            final uploadInputElement = html.FileUploadInputElement();
            uploadInputElement.multiple = false;
            uploadInputElement.draggable = true;
            uploadInputElement.click();
            uploadInputElement.onChange.listen((event) {
              final file = uploadInputElement.files?.first;
              if (file != null) {
                loading(() async {
                  final formData = html.FormData();
                  formData.appendBlob("avatarfile", file.slice(), file.name);
                  formData.append("memberId", Provider.memberId);
                  Api.getInstance().uploadAvatarFromHtml(formData, (e) {
                    if (e['code'] == 0) {
                      setState(() {
                        _avatarFilePath = e['data']['url'];
                      });
                    } else {
                      ThemeSnackBar.show(context, e['msg']);
                    }
                  });
                });
              }
            });
          }
        });
      });
    } else {
      loading(() async {
        final picker = ImagePicker();

        ImageSource source;
        if (type == '拍照') {
          source = ImageSource.camera;
        } else {
          source = ImageSource.gallery;
        }
        final pickerFile =
            await picker.pickImage(source: source, imageQuality: 50);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path,
              //图片资源
              maxHeight: 500,
              maxWidth: 500,
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
              //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance()
                .uploadAvatar(Provider.memberId, filepath); //pickerFile.path
            if (res['code'] == 0) {
              final data = res['data'];
              setState(() {
                _avatarFilePath = data['url'];
                ThemeSnackBar.show(context, res['msg']);
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
            print("filepath-----$filepath");
          }
        }
      });
    }
  }
}
